package com.aaron.kjviewutils.car;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.eventBus.BundleEventMsg;
import com.aaron.kjviewutils.footballleague.TabPagerStateAdapter;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.aaron.kjviewutils.spinkit.PoponDismissListener;
import com.aaron.kjviewutils.stock.MsgPopWin;
import com.aaron.kjviewutils.stock.StockActivity;
import com.github.ybq.android.spinkit.Style;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aaron.kjviewutils.stock.MsgPopWin.MsgType.MSG_CARS_INFO;

/**
 * Created by Aaron on 2017/3/2.
 */

public class CarsActivity extends BaseActivity {

    @Bind(R.id.carToolBar)
    Toolbar carToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.carTabs)
    TabLayout carTabs;
    @Bind(R.id.carViewpager)
    ViewPager carViewpager;

    private CarService carService;
    private Call<CarBean> carCall;
    private TabPagerStateAdapter adapter;
    private List<Fragment> fragments;
    private String carName;
    private Call<CarInfoBean> carInfoCall;
    private MsgPopWin msgPopWin;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        closeSelf(CarsActivity.this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(BundleEventMsg msg)
    {
        switch (msg.getType())
        {
            case BUNDLE_CAR_INFO:
            {
                Bundle bundle = msg.getBundle();
                carName = bundle.getString("name");
                mHandler.postDelayed(runnableLoadCarInfo, 1000);
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_cars);
        ButterKnife.bind(this);
        initTitle();
        mHandler.postDelayed(runnableLoadData, 1000);
    }

    Runnable runnableLoadCarInfo = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(carToolBar, Gravity.CENTER, 0, 0);
            }
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            carService = retrofit.create(CarService.class);
            carInfoCall = carService.obtainCar(carName);
            carInfoCall.enqueue(new Callback<CarInfoBean>() {
                @Override
                public void onResponse(Call<CarInfoBean> call, Response<CarInfoBean> response) {
                    carInfoCall.cancel();
                    if(null!=progress)
                    {
                        progress.dismissView();
                    }
                    CarInfoBean carInfo = response.body();
                    if(null!=carInfo)
                    {
                        if("200".equals(carInfo.retCode))
                        {
                            if(null==msgPopWin)
                            {
                                msgPopWin = new MsgPopWin(CarsActivity.this, CarsActivity.this);
                            }
                            msgPopWin.showUi(carInfo, MSG_CARS_INFO);
                            msgPopWin.showAtLocation(carToolBar, Gravity.CENTER, 0, 0);
                            msgPopWin.setOnDismissListener(new PoponDismissListener( CarsActivity.this ));
                        }
                        else
                        {
                            showMsg(carInfo.msg);
                        }
                    }
                    else
                    {
                        showMsg("加载数据失败");
                    }
                }

                @Override
                public void onFailure(Call<CarInfoBean> call, Throwable t) {
                    carInfoCall.cancel();
                    if(null!=progress)
                    {
                        progress.dismissView();
                    }
                    showMsg("加载数据失败");
                }
            });
        }
    };

    Runnable runnableLoadData = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(carToolBar, Gravity.CENTER, 0, 0);
            }
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            carService = retrofit.create(CarService.class);
            carCall = carService.obtainCars();
            carCall.enqueue(new Callback<CarBean>() {
                @Override
                public void onResponse(Call<CarBean> call, Response<CarBean> response) {
                    carCall.cancel();
                    if(null!=progress)
                    {
                        progress.dismissView();
                    }
                    CarBean carBean = response.body();
                    if(null!=carBean)
                    {
                        if("200".equals(carBean.retCode))
                        {
                            initTabs(carBean);
                        }
                        else
                        {
                            showMsg(carBean.msg);
                        }
                    }
                    else
                    {
                        showMsg("加载数据失败");
                    }
                }

                @Override
                public void onFailure(Call<CarBean> call, Throwable t) {
                    carCall.cancel();
                    if(null!=progress)
                    {
                        progress.dismissView();
                    }
                    showMsg("加载数据失败");
                }
            });
        }
    };

    private void initTabs(CarBean carBean)
    {
        fragments = new ArrayList<Fragment>();
        if(null!=carBean)
        {

            List<CarBean.CarInfo> datas = carBean.result;
            if(null!=datas&&!datas.isEmpty())
            {
                for(CarBean.CarInfo carInfo:datas)
                {
                    CarFragment weChatFragment = new CarFragment();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("carInfo", carInfo);
                    weChatFragment.setArguments(bundle);
                    fragments.add(weChatFragment);
                }
                adapter = new TabPagerStateAdapter(getSupportFragmentManager(), fragments);
                carViewpager.setAdapter(adapter);
                carTabs.setupWithViewPager(carViewpager);
                carTabs.setTabMode(TabLayout.MODE_SCROLLABLE);
                int size = datas.size();
                for(int i=0; i<size; i++)
                {
                    CarBean.CarInfo carInfo = datas.get(i);
                    //初始化tabs
                    TabLayout.Tab tab = carTabs.getTabAt(i);
                    tab.setCustomView(getTabsItem(carInfo.name));
                }
            }
        }
    }

    private View getTabsItem(String tag)
    {
        View view = inflater.inflate(R.layout.tas_item, null, false);
        TextView tabsTag = (TextView) view.findViewById(R.id.tabsTag);
        tabsTag.setText(tag);
        return view;
    }

    private void initTitle()
    {
        carToolBar.setTitle("");
        barTitle.setText("汽车信息查询");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        carToolBar.setNavigationIcon(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            //关闭
            closeSelf(CarsActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=msgPopWin)
        {
            msgPopWin.dismissView();
        }
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadData);
            mHandler.removeCallbacks(runnableLoadCarInfo);
        }
        if(null!=carCall)
        {
            carCall.cancel();
        }
        if(null!=carInfoCall)
        {
            carInfoCall.cancel();
        }
        ButterKnife.unbind(this);
    }
}
